package com.pjchat.pjchatclient.handlerImpl;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.util.Iterator;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;

import com.ita.im.model.Unit;
import com.ita.im.model.User;
import com.pjchat.pjchatclient.frame.MyClientFrame;
import com.pjchat.pjchatclient.handler.BasicHandler;
import com.pjchat.pjchatclient.sender.ForwardSender;

public class HandlerForList extends BasicHandler {
	private static HandlerForList instance;

	private HandlerForList() {

	}

	public static HandlerForList getInstance() {
		if (instance == null) {
			instance = new HandlerForList();
		}
		return instance;
	}

	@Override
	public Unit doRequest(JFrame frame, Unit unit, BufferedReader br,
			BufferedWriter bw) {
		ForwardSender.send(bw, unit);
		return null;
	}

	@Override
	public Unit doResponse(JFrame frame, Unit unit, BufferedReader br,
			BufferedWriter bw) {
		MyClientFrame myFrame = (MyClientFrame) frame;
		@SuppressWarnings("unchecked")
		List<User> userList = (List<User>) unit.getValue().get("users");
		if (userList != null) {
			// myFrame.getMyFriendList().sets

			// 复用之前的model
			DefaultListModel<String> model = myFrame.getMyFriendListModel();
			model.removeAllElements();
			Iterator<User> iterator = userList.iterator();
			while (iterator.hasNext()) {
				model.addElement(iterator.next().getName());
			}

			// 新建一个model，重设jlist的model
			// DefaultListModel<String> model = new DefaultListModel<String>();
			// Iterator<User> iterator = userList.iterator();
			// while (iterator.hasNext()) {
			// model.addElement(iterator.next().getName());
			// }
			// myFrame.getMyFriendList().setModel(model);

			if (!userList.contains(myFrame.getTarget())) {
				myFrame.setTarget(null);
				myFrame.getMyTarget().setText("");
			}
			myFrame.setUserList(userList);
		}
		return null;
	}

}
